// pages/login/login.js

const app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    loading: false,
    xh: "",
    mm: "",
    ccUrl: "",
    cookie: "",
    cookieDoor: "",
    fid: "",
    fid2: "",
    rememberMe: true,
    info: '由于教务网问题，可能需要尝试多次登录',
    lableText1: '教务网',
    lableText2: '教务网',
    subTitle: '请先登录',
    isJw: true,
    hasRememberMeInfoDoor: false,
  },


  checkboxChange: function(e) {
    this.setData({
      rememberMe: !this.data.rememberMe
    })
  },

  getCheckCodeUrl: function() {
    let that = this;
    let xh = this.data.xh;
    let cImgUrl = this.data.ccUrl;

    wx.request({
      url: app.globalData.apiAccessSuffix + '/login/gcc',
      data: {
        xh: xh,
        curImgUrl: cImgUrl
      },
      header: {
        "CookieDoor": that.data.cookieDoor,
      },
      dataType: 'json',
      success: function(res) {
        let result = res.data;
        console.log(result);

        let obj = result.data;
        let ckx = obj.checkCodeUrlSuffix;
        // if (ckx.indexOf('-1') >= 0) {
        that.setData({
          ccUrl: app.globalData.imgAccessUrlSuffix + "/" + obj.checkCodeUrlSuffix,
          cookie: obj.cookie
        });
        // } else {
        //   wx.showToast({
        //     title: '服务正在开小差，请稍后再试',
        //     icon: 'none',
        //     duration: 2000,
        //     mask: true,
        //     complete: function(res) {},
        //   })
        // }
      }
    });
  },


  loginSubmit: function(e) {
    let that = this;
    let rememberMe = that.data.rememberMe;
    let ffid = that.data.fid;

    console.log(e);
    let xh = e.detail.value.xhIpt;
    let mm = e.detail.value.mmIpt;

    if (ffid == "-1") {
      switch (ffid) {
        case '104':
          wx.request({
            url: app.globalData.apiAccessSuffix + '/query/pegrade',
            data: {
              xh: xh,
              mm: mm,
            },
          });
          break;
        case '105':
          wx.redirectTo({
            url: '../newcredit/newcredit?xh=' + xh + '&mm=' + mm,
          })
          break;
        default:
          let cc = e.detail.value.ccIpt.trim();
          if (xh === '' || mm === '' || cc === '') {
            wx.showToast({
              title: '请不要留空',
              icon: 'none',
              duration: 2000
            });
            return;
          }
          that.setData({
            loading: true,
          });
          wx.request({
            url: app.globalData.apiAccessSuffix + '/login/li',
            data: {
              xh: xh,
              mm: mm,
              cc: cc,
              fId: that.data.fid,
            },
            header: {
              "CookieCC": that.data.cookie,
              "CookieDoor": that.data.cookieDoor
            },
            dataType: 'json',
            success(res) {
              let obj = res.data;
              console.log(obj);
              console.log(that.data.fid2);
              // return;
              if (obj.success) {
                wx.showToast({
                  title: '登录成功',
                  icon: 'success',
                  duration: 2000
                });
                wx.setStorage({
                  key: 'xh',
                  data: xh,
                });
                wx.setStorage({
                  key: 'mm',
                  data: mm,
                });
                if (rememberMe) {
                  wx.setStorage({
                    key: 'hasRememberMe',
                    data: true,
                  });
                } else {
                  wx.setStorage({
                    key: 'hasRememberMe',
                    data: false,
                  });
                }
                let ffId;
                if(that.data.fid == "-1") {
                  ffId = that.data.fid2;
                } else{
                  ffId = that.data.fid;
                }
                let destUrl = '';
                let cookie = that.data.cookieDoor + "; " + that.data.cookie;
                switch (ffId) {
                  case '0':
                    destUrl = '../course/course?local=0&xh=' + xh + '&mm=' + mm + '&cookie=' + encodeURIComponent(cookie);
                    break;
                  case '101':
                    destUrl = '../grade/grade?xh=' + xh + '&mm=' + mm + '&fid=' + ffId + '&cookie=' + encodeURIComponent(cookie);
                    break;
                  case '102':
                    destUrl = '../credit/credit?xh=' + xh + '&mm=' + mm + '&cookie=' + encodeURIComponent(cookie);
                    break;
                  case '103':
                    destUrl = '../grade/grade?xh=' + xh + '&mm=' + mm + '&fid=' + ffId + '&cookie=' + encodeURIComponent(cookie);
                    break;
                  default:
                    wx.showToast({
                      title: '非法请求',
                      icon: 'none',
                      duration: 2000,
                      mask: true,
                      success: function(res) {},
                      fail: function(res) {},
                      complete: function(res) {
                        wx.navigateBack({
                          delta: 1,
                        })
                      },
                    })
                    return;
                };
                wx.redirectTo({
                  url: destUrl,
                });
              } else {
                that.getCheckCodeUrl();
                wx.showToast({
                  title: obj.msg,
                  icon: 'none',
                  duration: 3000
                });
              }
              that.setData({
                loading: false,
              });
            }

          });
          break;
      }
    } else {
      this.loginInfoDoor(xh, mm);
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {

    console.log("ONLOAD>>>>>>");
    let that = this;

    let xh = wx.getStorageSync('xh');
    let mm = wx.getStorageSync('mm');


    let fId = options.fid;
    let fId2 = options.fid2;

    if (fId2 != null && fId2 != "") {
      this.setData({
        fid2: fId2
      });
    }
    this.setData({
      xh: xh,
      fid: fId,
      mm: mm,
    });

    if (fId != "-1") {
      this.checkLoginInfoDoor();
    } else {
      let cookieDoor = decodeURIComponent(options.cookieDoor);
      that.setData({
        "cookieDoor": cookieDoor
      });

      that.getCheckCodeUrl();
    }


    // if (this.hasRememberMeInfoDoor) {
    //   switch (fId) {
    //     case '104':
    //       this.setData({
    //         lableText1: '体测网站',
    //         lableText2: '体测网站',
    //         subTitle: '可能需要内网，密码可能等于学号',
    //         isJw: false,
    //       });
    //       break;
    //     case '105':
    //       this.setData({
    //         lableText1: '素质拓展系统网站',
    //         lableText2: '素质拓展系统网站',
    //         subTitle: '[ http://sjjx.njit.edu.cn:8080/]\r\n需要内网，密码可能等于学号',
    //         isJw: false,
    //       });
    //       break;
    //     default:
    //       break;
    //       // 登录到教务网
    //       // this.loginInfoDoor();
    //       this.getCheckCodeUrl();
    //       wx.getStorage({
    //         key: 'hasRememberMe',
    //         success: function(res) {
    //           if (res.data) {
    //             wx.getStorage({
    //               key: 'mm',
    //               success: function(res) {
    //                 that.setData({
    //                   mm: res.data
    //                 });
    //               },
    //             });
    //           }
    //         },
    //       })
    //       break;
    //   }
    // } else {

    // }
  },

  checkLoginInfoDoor: function() {
    let hasRememberMeInfoDoor = wx.getStorageSync('hasRememberMeInfoDoor');
    let infoDoorUsername = wx.getStorageSync('infoDoorUsername');
    let infoDoorPwd = wx.getStorageSync('infoDoorPwd');
    this.setData({
      hasRememberMeInfoDoor: hasRememberMeInfoDoor
    })
    if (hasRememberMeInfoDoor != null && hasRememberMeInfoDoor && infoDoorUsername != "" && infoDoorPwd != "") {
      this.loginInfoDoor(infoDoorUsername, infoDoorPwd);
    } else {
      this.setData({
        lableText1: '信息门户',
        lableText2: '信息门户',
        isJw: false,
      });
    }
  },

  loginInfoDoor: function(username, pwd) {
    let that = this;
    wx.showLoading({
      title: '正在登录信息门户，请稍后...',
    });
    wx.request({
      url: app.globalData.apiAccessSuffix + '/login/infoDoor',
      data: {
        xh: username,
        pwd: pwd
      },
      dataType: 'json',
      success: function(res) {
        let obj = res.data;
        if (!obj.success) {
          wx.showToast({
            title: "用户名或密码错误",
            icon: 'none',
            duration: 3000
          });
          return;
        }

        // 信息门户登录成功
        let rememberMe = that.data.rememberMe;
        let cookieDoor = obj.message;
        if (rememberMe) {
          wx.setStorage({
            key: 'hasRememberMeInfoDoor',
            data: true,
          });
          wx.setStorage({
            key: 'infoDoorUsername',
            data: username,
          });
          wx.setStorage({
            key: 'infoDoorPwd',
            data: pwd,
          });
        } else {
          wx.setStorage({
            key: 'hasRememberMeInfoDoor',
            data: false,
          });
        }

        that.setData({
          cookieDoor: obj.message,
        });
        wx.showToast({
          title: '信息门户登录成功，3s后定向到教务网登录页面',
          icon: 'none',
          duration: 3000,
          mask: true,
          complete: function(res) {},
        });
        wx.redirectTo({
          url: "../login/login?fid=-1&fid2=" + that.data.fid + "&cookieDoor=" + encodeURIComponent(cookieDoor),
        });
      },
      complete: function() {
        wx.hideLoading();
      }
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
    // this.setData({
    //   fid: 
    // })
    // this.checkLoginInfoDoor();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})